package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.domain.dto.RegisterDTO;
import com.ruoyi.system.domain.dto.SendSmsDTO;
import com.ruoyi.system.service.UserService;
import com.ruoyi.system.web.SmsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("app/api/user")
@Api(tags = "用户注册相关接口")
@Slf4j
public class RegisterController extends BaseController {
    /**
     * app用户注册
     */

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SmsUtils smsUtils;

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public R register(@RequestBody RegisterDTO registerDTO){
        userService.register(registerDTO);
        return R.ok("ok");
    }
//    @ApiOperation(value = "用户注册")
//    @PostMapping("/register")
//    public AjaxResult register(@RequestBody RegisterDTO registerDTO){
////        userService.register(registerDTO);
//        AjaxResult ajax=new AjaxResult();
//        ajax.put("code",5002);
//        ajax.put("msg","验证码返回错误");
//        return ajax;
//    }

    /**
     * 发送短信验证码
     * @param sendSmsDto
     * @return
     */
    @ApiOperation(value = "验证码发送")
    @PostMapping("/sendSms")
    public R sendSms(@RequestBody SendSmsDTO sendSmsDto ) throws Exception {
        String codeKey=smsUtils.sendSms(sendSmsDto.getPhoneNumber());
//        System.out.println("参数中的手机号："+sendSmsDto.getPhoneNumber());
//        System.out.println("控制层中的验证码："+codeKey);
        if(codeKey !=null){
           System.out.println("缓存前的验证码："+codeKey);
           //缓存验证码在redis中过期时间为1分钟
           redisTemplate.opsForValue().set("keyCode",codeKey,20, TimeUnit.MINUTES);
            System.out.println("缓存后的验证码："+codeKey);
            return R.ok("ok");
       }else {
            return R.fail("短信发送失败");
        }
//        return R.ok();
    }
}
